package net.sureon.web.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.app.AppContext;
import net.sureon.app.UserSession;
import net.sureon.biz.CompanyMgr;
import net.sureon.biz.UserBO;
import net.sureon.biz.UserMgr;
import net.sureon.common.SureonConstants;
import net.sureon.web.Login;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class Jump implements Controller {
    private static final Log logger = LogFactory.getLog(Login.class);
	private UserMgr userMgr;

	/**
	 * @return the userMgr
	 */
	public UserMgr getUserMgr() {
		return userMgr;
	}

	/**
	 * @param userMgr the userMgr to set
	 */
	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

		logger.info("go to jump page, adminUser=" + AppContext.getUserID());
		
		UserBO dummy = null;
		long targetCompanyID = 0;
		try{
			targetCompanyID = Long.parseLong(request.getParameter("companyID"));
			dummy = userMgr.getAdminUser(targetCompanyID);
		}catch(Exception e){
			logger.error("targetCompanyID:" + targetCompanyID, e);
		}
        if(dummy == null || dummy.getUserVO() == null){
        	response.sendRedirect(request.getContextPath() + "/sysAdmin/manageCustomer.do");
        }else{
	        UserSession sess = (UserSession) request.getSession().getAttribute(
	            UserSession.HTTP_SESSION_KEY);
	        if (sess != null) {
	            sess.reset();
	        }
	        request.getSession().removeAttribute(UserSession.HTTP_SESSION_KEY);
	        request.getSession().removeAttribute(SureonConstants.SESSION_ATTR_COMPAYCONFIG);
	
	        UserSession dummySess = new UserSession(dummy);
	        AppContext.setCurrentUserSession(dummySess);
	        request.getSession().setAttribute(UserSession.HTTP_SESSION_KEY, dummySess);
	        logger.info("jumpping to company:" + targetCompanyID + ", as user: " + dummy.getUserID());
	        response.sendRedirect(request.getContextPath() + "/user/myDailyTiming.do");
        }
        return null;
    }
}
